﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="AjaxAction.js" />


	var grid;
	var caretaker;
	var keyboardHandler;
    
    var $model_main;    	
    
    var $fieldOptions = new Object();
    
    var $schema_main = [
	    {
		    headerText:"Id",
		    propertyName:"Moniker",
		    type:"number",
		    className:"id"
	    },
	    {
		    headerText:"Deliverable",
		    propertyName:"DeliverableId",
		    type:"string",
		    editable:false,
		    options:$fieldOptions.deliverable,
		    validation:DataGrid.Validation.REQUIRED,
		    className:"deliverable"
	    },
	    {
		    headerText:"Title",
		    propertyName:"Title",
		    type:"string",
		    editable:true,
		    textMode:"multiline",		    
		    className:"title"
	    },
	    {
		    headerText:"Days<br>Open",
		    propertyName:"DaysOpen",
		    type:"number",
		    className:"dayOpen"
	    },
	    {
		    headerText:"Created By",
		    propertyName:"CreatedBy",
		    type:"string",
		    editable:true,
		    validation:DataGrid.Validation.REQUIRED,
		    className:"status"
	    },
	    {
		    headerText:"Decision",
		    propertyName:"Decision",
		    type:"string",
		    textMode:"multiline",
		    editable:true,
		    className:"decision"
	    },
	    {
		    headerText:"S",
		    propertyName:"Severity",
		    type:"number",
		    editable:true,
		    className:"weight"
	    },
	    {
		    headerText:"T",
		    propertyName:"Triaged",
		    type:"boolean",
		    editable:true,
            className:"triaged"
	    },
	     {
		    headerText:"",
		    type:"linkbutton",
		    text:"Edit",
		    commandName:"edit",
		    className:"btnEdit"
	    },
	     {
		    headerText:"",
		    type:"linkbutton",
		    text:"Delete",
		    commandName:"delete",
		    className:"btnDelete"
	    }
    ];
    
	Event.observe(window, "load", init, false);
	
	function init() {
	    
		// keyboard
		keyboardHandler = new KeyboardHandler();
		keyboardHandler.addHandler("z", KeyboardHandler.Keys.ALT, undo.bindAsEventListener(this));
		keyboardHandler.addHandler("z", KeyboardHandler.Keys.ALT | KeyboardHandler.Keys.SHIFT, redo.bindAsEventListener(this));
		keyboardHandler.addHandler("y", KeyboardHandler.Keys.ALT, redo.bindAsEventListener(this));
		// caretaker
		caretaker = new CommandCaretaker();
		caretaker.onChange = caretaker_onChange;
		caretaker.onRedo = caretaker_onUndoRedo;
		caretaker.onUndo = caretaker_onUndoRedo;
        
        // fillDeliverablesValues();
        fillDeliverablesValuesPage();
	}
	
	function createGrid() {
	    grid = new DataGrid();		
		Event.observe(grid, "row_edit_commit", this.gridEditCommit.bindAsEventListener(this));
		Event.observe(grid, "row_command", this.gridCommand.bindAsEventListener(this));
		Event.observe(grid, "row_created", this.gridRowRendered.bindAsEventListener(this));
	}
	
	function bindGrid(nTriaged) {
	    var options = {url: $getUrl+'&nTriaged='+nTriaged};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");
	    new HttpHelper.AjaxAction().invoke(options, null, onGetCompleted);
	}
	
	function bindGridPage(nPage,nTriaged) {
	    if (nPage<0)
	        return;

	    if ($nPageRows==0 && nPage>$nPageGrid)
	        return;

	    if ($nGridPages>0 && nPage>=$nGridPages)
	        return;

	    var options = {url: $getUrlPage+'&nPage='+nPage+'&nTriaged='+nTriaged};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");
	    $nPageGrid = nPage;
	    new HttpHelper.AjaxAction().invoke(options, null, onGetPageCompleted);
	}
	
	function onGetCompleted(executor, eventArgs) {
        Sys.UI.DomElement.addCssClass($get("progressBar"), "off");
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            $model_main = executor.get_object();
            $nPageRows = $model_main.length;
            
            if (grid.inited) {
                grid.model = $model_main;
                grid.refresh();
            }
            else   
                grid.initialize($('grid'), $schema_main, $model_main, true);		        
                
            $get('pageNumber').innerHTML = '';
            $get('pageNumber2').innerHTML = '';
        } 
        if (executor.get_statusCode() === 500) {
            alert(executor.get_responseData());
        }        
    }

	function onGetPageCompleted(executor, eventArgs) {
        Sys.UI.DomElement.addCssClass($get("progressBar"), "off");
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            var defectsPage = executor.get_object();
            $model_main = defectsPage.Defects;
            $nPageRows = defectsPage.Defects.length;
            
            if (grid.inited) {
                grid.model = $model_main;
                grid.refresh();
            }
            else   
                grid.initialize($('grid'), $schema_main, $model_main, true);		        
                
            $nPageGrid = defectsPage.NoPage;                
            $nGridPages = defectsPage.NoPages;
            
            $get('pageNumber').innerHTML = 'Page ' + ($nPageGrid+1) + '/' + $nGridPages;
            $get('pageNumber2').innerHTML = 'Page ' + ($nPageGrid+1) + '/' + $nGridPages;
        } 
        if (executor.get_statusCode() === 500) {
            alert(executor.get_responseData());
        }        
    }

    function refresh() {        
//        bindGrid();
        bindGridPage($nPageGrid, $nTriaged);
    }

    function fillDeliverablesValuesPage() {
        var options = {url: $getDeliverablesUrl, format: 'json'};
        
	    new HttpHelper.AjaxAction().invoke(options, null, onGetDeliverablesPostCompletedPage);        
    }
    
    function onGetDeliverablesPostCompletedPage(executor, eventArgs) {
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            $fieldOptions.deliverable = executor.get_object();
            $schema_main[1].options = $fieldOptions.deliverable;
            createGrid();
		    bindGridPage(0, $nTriaged);
        } else { 
            alert('The application is not available. Try again later.');
        }      
    }
    
    function fillDeliverablesValues() {
        var options = {url: $getDeliverablesUrl, format: 'json'};
        
	    new HttpHelper.AjaxAction().invoke(options, null, onGetDeliverablesPostCompleted);        
    }
    
    function onGetDeliverablesPostCompleted(executor, eventArgs) {
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            $fieldOptions.deliverable = executor.get_object();
            $schema_main[1].options = $fieldOptions.deliverable;
            createGrid();
		    bindGrid($nTriaged);
        } else { 
            alert('The application is not available. Try again later.');
        }      
    }
    
    function saveDefects() {
        var options = {url: $postUrl, format: 'json'};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");  
        var changeset = [];
        for (var i=0; i<$model_main.length; i++) {
            if($model_main[i].changed) {
                changeset.push($model_main[i]);
            }
        }
        var data = Sys.Serialization.JavaScriptSerializer.serialize(changeset);      
	    new HttpHelper.AjaxAction().invoke(options, data, onPostCompleted);        
    }
    
    function deleteDefect(id) {
        var options = {url: $deleteUrl + id, format: 'json'};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");  
        
        var data = Sys.Serialization.JavaScriptSerializer.serialize(id);      
	    new HttpHelper.AjaxAction().invoke(options, data, onPostCompleted);        
    }
    
    function onPostCompleted(executor, eventArgs) {
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            grid.refresh();            
        } else { 
            alert('The application is not available. Try again later.');
        }        
        Sys.UI.DomElement.addCssClass($get("progressBar"), "off");        
    }
    
    function caretaker_onChange(undoCount, redoCount) {		
	}

	function caretaker_onUndoRedo(cmd) {
		// TODO
	}

	function undo() {
		caretaker.undo();
	}

	function redo() {
		caretaker.redo();
	}

    function getStyle(oElm, strCssRule){
	    var strValue = "";
	    if(document.defaultView && document.defaultView.getComputedStyle){		    
		    strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	    }
	    else if(oElm.currentStyle){	    
		    strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			    return p1.toUpperCase();
		    });		    
		    strValue = oElm.currentStyle[strCssRule];
	    }
	    return strValue;
    }
    
    function gridRowRendered(e) {
	}
	
	function setFixedStyles(td) {
	    td.style.backgroundColor = getStyle(td, 'background-color');			    
        td.style.borderColor = getStyle(td, 'border-color');
        td.style.borderWidth = getStyle(td, 'border-width');
        td.style.borderStyle = getStyle(td, 'border-style');
        td.style.textAlign = getStyle(td, 'text-align');
	}
	
	function gridEditCommit(e) {
		// DataGridRowEditCommand(grid, gridRow, dataItem, oldValues, newValues)
		var eData = e.event_data.data;
		eData.dataItem.changed = true;
		var cmd = new DataGridRowEditCommand(e.event_data.event_target, eData.dataItem, eData.rowIndex, eData.oldValues, eData.newValues);
		caretaker.pushCommand( cmd );
		cmd.commit();
	}

    function gridCommand(e) {
        switch (e.event_data.data.commandName)
        {
            case "edit":
        		var data = e.event_data.data;
	            $editUrl += '/';
	            $editUrl += data.dataItem.Moniker;
	            location.href = $editUrl;
                break;
            case "delete":
                if(confirm("Are you sure you want to delete the defect # "+e.event_data.data.dataItem.Moniker+"?")) {
        		    var data = e.event_data.data;
	                deleteDefect(data.dataItem.Id);
			        var grid = e.event_data.event_target;
			        var rowIndex = e.event_data.data.rowIndex;			        
			        var cmd = new DataGridRowDeleteCommand(grid, rowIndex);
			        caretaker.pushCommand(cmd);
			        cmd.commit();
                }
                break;
        }
	}
	
